package com.lambkit.node;

import com.google.common.collect.Lists;
import com.jfinal.handler.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class NodeHttpHandler extends Handler {

	private List<NodeHttpInterceptor> inters;
	private String nodeTarget = "/lambkit/node";
	
	public NodeHttpHandler() {
		inters = Lists.newArrayList();
		nodeTarget += "/" + LambkitNodeManager.me().getNode().getId();
	}
	
	public NodeHttpHandler(String nodeTarget) {
		inters = Lists.newArrayList();
		nodeTarget += "/" + LambkitNodeManager.me().getNode().getId();
		this.setNodeTarget(nodeTarget);
	}
	
	public void addInterceptor(NodeHttpInterceptor pipline) {
		inters.add(pipline);
	}
	
	@Override
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		
		if(target.equals(nodeTarget)) {
			NodeHttpAction nodeHttpAction = new NodeHttpAction(request, response);
			NodeHttpPipline pipline = new NodeHttpPipline(nodeHttpAction, inters);
			pipline.invoke();
			isHandled[0] = true;
			return;
		} else {
			next.handle(target, request, response, isHandled);
		}
	}


	public String getNodeTarget() {
		return nodeTarget;
	}

	public void setNodeTarget(String nodeTarget) {
		this.nodeTarget = nodeTarget;
	}

}
